package com.pdformparent;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import com.dengpp.pdform.base.BaseCustomFormView;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于 XML 布局的自定义视图
 */
public class XmlBasedCustomView extends BaseCustomFormView {
    private EditText input1, input2;
    private CheckBox option1, option2;
    private Map<String, Object> currentValue = new HashMap<>();

    @Override
    protected View onCreateView(Context context) {
        // 加载 XML 布局
        View view = LayoutInflater.from(context).inflate(R.layout.custom_complex_layout, null);

        // 初始化视图组件
        input1 = view.findViewById(R.id.input1);
        input2 = view.findViewById(R.id.input2);
        option1 = view.findViewById(R.id.option1);
        option2 = view.findViewById(R.id.option2);

        // 设置监听器
        setupListeners();

        return view;
    }

    @Override
    protected void onBindData(Object value) {
        if (value instanceof Map) {
            currentValue = new HashMap<>((Map<String, Object>) value);

            input1.setText((String) currentValue.get("input1"));
            input2.setText((String) currentValue.get("input2"));
            option1.setChecked(Boolean.TRUE.equals(currentValue.get("option1")));
            option2.setChecked(Boolean.TRUE.equals(currentValue.get("option2")));
        }
    }

    @Override
    public Object getCurrentValue() {
        return currentValue;
    }

    private void setupListeners() {
        // 输入框监听
        input1.addTextChangedListener(createTextWatcher("input1"));
        input2.addTextChangedListener(createTextWatcher("input2"));

        // 复选框监听
        option1.setOnCheckedChangeListener(createCheckboxListener("option1"));
        option2.setOnCheckedChangeListener(createCheckboxListener("option2"));
    }

    private TextWatcher createTextWatcher(final String key) {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                currentValue.put(key, s.toString());
                notifyValueChanged(currentValue);
            }
        };
    }

    private CompoundButton.OnCheckedChangeListener createCheckboxListener(final String key) {
        return (buttonView, isChecked) -> {
            currentValue.put(key, isChecked);
            notifyValueChanged(currentValue);
        };
    }
}
